import { _decorator, Color, Component, EventTouch, instantiate, Label, Node, NodeEventType, Prefab, resources, tween, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('GlobalUtil')
class GlobalUtil{
    static _instance:GlobalUtil = null;
    public static getInstance():GlobalUtil{
        if(this._instance == null){
            this._instance = new GlobalUtil();
        }
        return this._instance;
    }

    //生成1个随机整数, [0,m) m不可取
    public getSingleRandomInt(m:number):number{
        return Math.floor(Math.random() * m);
    }

    //生成多个随机整数(不重复). count:随机数个数, [n,m)为可取范围, m不可取
    public getMultiRandomInt(count:number, n:number, m:number) {
        if (count > m - n) {
            console.error("随机数取值数量大于可取数量");
            return;
        }
        let arr: number[] = [];
        for (let i = 0; i < count; i++) {
            let num = Math.floor(Math.random() * (m - n) + n);
            while (arr.indexOf(num) != -1) {
                num = Math.floor(Math.random() * (m - n) + n);
            }
            arr.push(num);
        }
        return arr;
    }

    //加载消息弹窗提示
    public LoadMessage(isClose: boolean, msg:string, parent: Node, targetlPos: Vec3, initialPos = new Vec3(-300, 950, 0), color: Color = new Color(255,255,255,255)) {
        let node: Node;
        let promise = new Promise((resolve, reject) => {
            resources.load("Prefabs/MessagePop", Prefab, (err, prefab) => {
                if (err) {
                    console.error(err);
                    reject(err);
                } else {
                    node = instantiate(prefab);
                    node.parent = parent;
                    node.setWorldPosition(initialPos);
                    let label = node.getChildByName("Context").getComponent(Label);
                    label.string = msg;
                    label.color = color;
                    tween(node).to(0.3, {worldPosition: targetlPos}).start();
                    if(isClose){
                        let panel = node.getChildByName("ConversationPanel_000");
                        panel.on(NodeEventType.TOUCH_END, () => {
                            
                            node.destroy();
                        })
                    }
                    resolve(node);
                }
            })
        });
        return promise;
    }

    public validateEmail(email: string): boolean {
        // 正则表达式用于校验邮箱格式
        const regex: RegExp = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        return regex.test(email);
    }

}
export const GLOBALUtil = GlobalUtil.getInstance();


